package com.wo.android.pockybill;

import java.util.ArrayList;
import java.util.List;

import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.wo.android.pockybill.adapter.BillAdapter;
import com.wow.wa.bill.serivce.BillService;
import com.wow.wa.bill.serivce.BillServiceImpl;
import com.wow.wa.bill.serivce.domain.BillListDTO;
import com.wow.wa.bill.util.Args;
import com.wow.wa.bill.vo.Bill;
import com.wow.wa.bill.vo.Card;
import com.wow.wa.ui.ItemDialog;
import com.wow.wa.util.DateFactory;
import com.wow.wa.util.DateFormat;
import com.wow.wa.util.DateUtil;

public class BillListViewFragment extends Fragment implements
		OnItemClickListener, OnItemSelectedListener, OnItemLongClickListener {

	private static final String TAG = BillListViewFragment.class
			.getSimpleName();
	private Context context;
	private List<Bill> result = new ArrayList<Bill>();
	private BillService service;
	private Card card;

	// private BillAdapter adapter = null;
	private TextView useMoney;
	private TextView range;

	// ----view
	private ListView listView = null;

	private static int DELLE_CODE = 0;
	private static int EDIT_CODE = 1;
	private static int PAYED_CODE = 2;
	private static int NOPAYED_CODE = 3;
	private View rootView;

	private BillListDTO dto = new BillListDTO();

	private Button createBtn;
	private Button deCreateBtn;

	public void AddOneBillFragment() {

	}

	@Override
	public void onDestroyView() {

		super.onDestroyView();
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.v(TAG, "onActivityResult requestCode=" + requestCode);

		try {
			Toast.makeText(this.getActivity(), "requestCode=" + requestCode,
					Toast.LENGTH_SHORT).show();
			switch (requestCode) {
			case Args.Common.EDIT_BILL_CODE:
			case Args.Common.ADD_BILL_CODE:

				final DownloadTask task = new DownloadTask(useMoney);
				task.execute("");
				break;
			}
		} catch (Exception e) {
			Log.v(TAG, "onActivityResult error=" + e);
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	public class DownloadTask extends AsyncTask<String, Void, Integer> {

		public TextView useMoney;

		public DownloadTask(TextView useMoney) {
			this.useMoney = useMoney;
		}

		@Override
		protected void onPreExecute() {

			rootView.findViewById(R.id.loadFrame).setVisibility(View.VISIBLE);
			rootView.findViewById(R.id.billListView).setVisibility(View.GONE);
			rootView.findViewById(R.id.payOutLayout).setVisibility(View.GONE);
			super.onPreExecute();
		}

		@Override
		protected Integer doInBackground(String... params) {
			try {

				result = service.getBill(dto.getCategory(), dto.getStartDate(),
						dto.getEndDate(), context);

			} catch (Exception e) {
				Log.v(TAG, "DownloadTask doInBackground e=" + e);
			}

			return result.size();
		}

		@Override
		protected void onPostExecute(Integer resultNo) {
			try {
				rootView.findViewById(R.id.loadFrame).setVisibility(View.GONE);
				if (resultNo > 0) {
					rootView.findViewById(R.id.billListView).setVisibility(
							View.VISIBLE);
					rootView.findViewById(R.id.payOutLayout).setVisibility(
							View.GONE);

				} else {
					rootView.findViewById(R.id.billListView).setVisibility(
							View.GONE);
					rootView.findViewById(R.id.payOutLayout).setVisibility(
							View.VISIBLE);

				}

				useMoney.setText("$:"
						+ service.stringByCountTotalMoneyWithNoPay(result));

				range.setText(dto.getFormat().toString());

				// FIXME
				// if (StringUtils.isBlank(card.getInDate())) {
				// range.setText(getString(R.string.notSetRang));
				// } else {
				// range.setText(getString(R.string.past) + "~" + end);
				// }

				listView.setAdapter(new BillAdapter(getActivity(), result, card));
				listView.setOnItemClickListener(BillListViewFragment.this);
				listView.setOnItemLongClickListener(BillListViewFragment.this);
			} catch (Exception e) {
				Log.v(TAG, "DownloadTask onPostExecute e=" + e);
			}
			super.onPostExecute(resultNo);
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		rootView = inflater.inflate(R.layout.activity_bill, container, false);

		setHasOptionsMenu(true);

		this.dto.setCategory(this.getArguments()
				.getString(Args.Common.PAY_TYPE));

		if (dto.getFormat() == null) {
			dto.setFormat(DateFactory.createYearMon());
		}

		this.card = (Card) this.getArguments().getSerializable(
				(Args.Common.CARD));

		this.dto.setFormat(DateFactory.createYearMon());
		this.dto.setStartDate(dto.getFormat() + "/00");
		this.dto.setEndDate(dto.getFormat() + "/99");

		Log.v(TAG, "payType=" + dto.getCategory());

		this.context = this.getActivity();
		this.service = new BillServiceImpl(this.context);
		this.listView = (ListView) rootView.findViewById(R.id.billListView);
		this.useMoney = (TextView) rootView.findViewById(R.id.useMoney);
		this.range = (TextView) rootView.findViewById(R.id.range);

		this.createBtn = (Button) rootView.findViewById(R.id.crease);
		this.deCreateBtn = (Button) rootView.findViewById(R.id.decrease);

		this.deCreateBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				DateUtil.deMonth(dto.getFormat());

				final DownloadTask task = new DownloadTask(useMoney);
				dto.setStartDate(dto.getFormat() + "/00");
				dto.setEndDate(dto.getFormat() + "/99");
				task.execute("");

			}
		});

		this.createBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				DateUtil.addMonth(dto.getFormat());

				dto.setStartDate(dto.getFormat() + "/00");
				dto.setEndDate(dto.getFormat() + "/99");
				final DownloadTask task = new DownloadTask(useMoney);
				task.execute("");
			};
		});

		result.clear();
		try {

			final DownloadTask task = new DownloadTask(useMoney);
			task.execute("");
		} catch (Exception e) {
			Log.v(TAG, "onCreateView error=" + e);
		}

		return rootView;

	}

	private ItemDialog getitemDialog(final int location) {
		String[] chooses = getResources().getStringArray(R.array.stateArray);
		final ItemDialog itemDialog = new ItemDialog(result.get(location)
				.getName(), context, chooses);
		itemDialog.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				int id = arg2;
				Bill selectBill = result.get(location);

				try {
					if (id == DELLE_CODE) {
						service.deeteBill(selectBill, context);
					} else if (id == EDIT_CODE) {
						Intent editIntent = new Intent(getActivity(),
								AddBillActivity.class);
						editIntent.putExtra(Args.DBSchema.BILL_TABLE_NAME,
								selectBill);
						startActivityForResult(editIntent,
								Args.Common.EDIT_BILL_CODE);
					} else if (id == PAYED_CODE) {
						service.updateBillToPayed(selectBill, context);
					} else if (id == NOPAYED_CODE) {
						service.updateBillToNoPayed(selectBill, context);
					}
					upDateListView();
					itemDialog.hide();

				} catch (Exception e) {
					Log.e(TAG, "error e=" + e);
				}

			}
		});
		return itemDialog;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {

		case R.id.action_add:
			final Intent it = new Intent(this.getActivity(),
					AddBillActivity.class);

			it.putExtra(Args.Common.CARD, card);
			it.putExtra(Args.Common.PAY_TYPE, this.getActivity().getActionBar()
					.getTitle());

			startActivityForResult(it, Args.Common.ADD_BILL_CODE);
			return false;

		}

		return super.onOptionsItemSelected(item);
	}

	public void upDateListView() {
		this.getActivity().runOnUiThread(new Runnable() {

			@Override
			public void run() {
				try {

					result = service.getBill(dto.getCategory(),
							dto.getStartDate(), dto.getEndDate(), context);

					listView.setAdapter(new BillAdapter(getActivity(), result,
							card));
					useMoney.setText("$:"
							+ service
									.stringByCountTotalMoneyWithNoPay(BillListViewFragment.this.result));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		});
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int location,
			long arg3) {
		Intent editIntent = new Intent(getActivity(), UpdateBillActivity.class);
		editIntent.putExtra(Args.Common.PAY_TYPE, this.getActivity()
				.getActionBar().getTitle());
		editIntent.putExtra(Args.Common.CARD, card);
		editIntent
				.putExtra(Args.DBSchema.BILL_TABLE_NAME, result.get(location));
		startActivityForResult(editIntent, Args.Common.EDIT_BILL_CODE);
	}

	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int location,
			long arg3) {
		Intent editIntent = new Intent(getActivity(), AddBillActivity.class);
		editIntent
				.putExtra(Args.DBSchema.BILL_TABLE_NAME, result.get(location));
		startActivityForResult(editIntent, Args.Common.EDIT_BILL_CODE);

	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		final ItemDialog itemDialog = getitemDialog(arg2);
		itemDialog.show();
		return false;
	}
}
